package y.q.h.config;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import y.q.h.entity.TAdmin;
import y.q.h.mapper.TAdminMapper;
import y.q.h.util.HttpContextUtil;
import y.q.h.util.JavaWebToken;
import y.q.h.util.apicontroller.R;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;


import static y.q.h.util.apicontroller.R.failed;

/**
* admin拦截器
*/
@Slf4j
public class Adminterpcter implements HandlerInterceptor {


    @Autowired
    private TAdminMapper tAdminMapper;

   @Override
   public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
       try {
           // 从请求头中获取token
           String token = request.getHeader("token");
           if (StringUtils.isBlank(token)) {
               token = request.getParameter("token");
           }
           System.err.println("=============token=========" + token);
           // 判断token
           if (token != null && token.trim().length() > 10) {
               Map<String, Object> map = JavaWebToken.parserJavaWebToken(token);
               if (map != null) {
                   System.err.println("=============jwt=========" + map);
                   TAdmin zhanghu = tAdminMapper.selectUsername(map.get("zhanghu").toString());
                   System.out.println("zhanghu = " + zhanghu);
                   if (zhanghu == null) {
                       setReturn(response, new R(-150, "请使用正确账户登录"));
                       return false;
                   }
                   //token里的时间
                   Integer data = (Integer) map.get("dateTime");
                   long number = data.longValue();
                   //当前时间
                   long verifyToken = System.currentTimeMillis() / 1000;
                   //计算登录的时间
                   long dateUltimately = verifyToken - number;
                   //大于三个小时就失效
                    if (dateUltimately>10800){
                        setReturn(response, new R(-110, "登录超时，请重新登录"));
                        return false;
                    }
                    return true;
               } else {
                   setReturn(response, new R(-130, "无权限，请登录"));
               }
           } else {
               setReturn(response, new R(-120, "未登录"));
           }
       } catch (Exception e) {
           e.printStackTrace();
           log.error("错误", e);
       }
       return false;
   }

   @Override
   public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {


   }

   @Override
   public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
       if (ex instanceof Exception) {
           log.error("错误", ex);
           response.setCharacterEncoding("utf-8");
           setReturn(response, failed("系统错误:" + ex.getMessage()));
       }

   }

   public static void setReturn(HttpServletResponse response, R r) throws IOException {
       response.setHeader("Access-Control-Allow-Credentials", "true");

       response.setHeader("Access-Control-Allow-Origin", HttpContextUtil.getOrigin());
       // UTF-8编码
       response.setCharacterEncoding("UTF-8");
       response.setContentType("application/json;charset=utf-8");
       response.getWriter().println(JSON.toJSON(r));
       response.getWriter().flush();
       response.getWriter().close();
   }
}
